import Duck from 'extensible-duck'
import produce from 'immer'

const initPage = { limit: 10 }
const initSearch = undefined
const initSort = 'name-asc'
const initValue = {
  page: initPage,
  sort: initSort,
  search: initSearch,
  modal: { isOpen: false, config: {} },
}
export default new Duck({
  namespace: 'admin',
  store: 'listTable',
  types: [
    'INIT',
    'RESET',
    'RECIVE_DATA',
    'NUM_PAGE',
    'CHANGE_SORT_METHOD',
    'CHANGE_SEARCH',
    'RECIVE_SEARCH_VALUE',
    'OPEN_MODAL',
    'CLOSE_MODAL',
  ],
  initialState: initValue,
  reducer: produce((draft, action, duck) => {
    switch (action.type) {
      case duck.types.INIT:
        draft.page = initPage
        draft.search = initSearch
        draft.sort = initSort
        break
      case duck.types.RESET:
        draft.page = initPage
        draft.search = initSearch
        draft.sort = initSort
        break
      case duck.types.RECIVE_DATA:
        draft.page.number = action.value
        break
      case duck.types.NUM_PAGE:
        draft.page.activeNum = action.value
        break
      case duck.types.CHANGE_SORT_METHOD:
        draft.sort = action.value
        break
      case duck.types.RECIVE_SEARCH_VALUE:
        draft.search = action.value
        break
      case duck.types.OPEN_MODAL:
        draft.modal.config = action.config
        draft.modal.isOpen = true
        break
      case duck.types.CLOSE_MODAL:
        draft.modal.isOpen = false
        break
      default:
        break
    }
  }),
  selectors: {
    isEmpty: state => state.listTable.page.number === 0,
    pageInfo: state => state.listTable.page,
    sortInfo: state => state.listTable.sort,
    searchInfo: state => state.listTable.search,
    modal: state => state.listTable.modal,
  },
  creators: duck => ({
    actionInit: () => ({ type: duck.types.INIT }),
    actionReset: () => ({ type: duck.types.RESET }),
    actionReciveData: value => ({ type: duck.types.RECIVE_DATA, value }),
    actionNumPage: value => ({ type: duck.types.NUM_PAGE, value }),
    actionSortMethod: value => ({ type: duck.types.CHANGE_SORT_METHOD, value }),
    actionChangeSearch: value => ({ type: duck.types.CHANGE_SEARCH, value }),
    actionReciveSearch: value => ({ type: duck.types.RECIVE_SEARCH_VALUE, value }),
    actionOpen: config => ({ type: duck.types.OPEN_MODAL, config }),
    actionClose: func => ({ type: duck.types.CLOSE_MODAL, func }),
  }),
})
